package com.alan.shiro.api.utils;

import com.alan.shiro.api.bean.User;
import com.alan.shiro.api.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/14 14:32
 * @Description: UserUtils
 */
public class UserUtils {

    private static UserService userService = null;

    public static Long getUserId(){
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        return userId;
    }


    public static User getCurrntUser(){
        return getUserService().findByUserId(getUserId());
    }

    private static UserService getUserService(){
        if(userService != null){
            return userService;
        }
        synchronized (UserUtils.class){
            if(userService != null){
                return userService;
            }
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            userService = applicationContext.getBean(UserService.class);
            return userService;
        }
    }

}
